import React from 'react'
import { Menu } from 'antd';
import MenuConfig from '../../config/menuConfig.js'
import './index.less';
import { NavLink } from 'react-router-dom'
import { connect } from 'react-redux'
import { switchMenu } from '../../redux/action'
const { SubMenu } = Menu;

class NavLeft extends React.Component {

  state = {
    currentKey: ''
  }

  handleClick = ({ item, key }) => {
    const { dispatch } = this.props
    dispatch(switchMenu(item.props.title))
    this.setState({
      currentKey: key
    })
  }

  componentWillMount() {
    const menuTreeNode = this.renderMenu(MenuConfig)
    let currentKey = window.location.hash.replace(/#|\?.+s/g, '')
    this.setState({
      currentKey,
      menuTreeNode
    })
  }

  /**
   * 获取菜单数据
   */
  renderMenu = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <SubMenu title={item.title} key={item.key}>
            { this.renderMenu(item.children) }
          </SubMenu>
        )
      }
      return <Menu.Item title={item.title} key={item.key}>
        <NavLink to={item.key}>{item.title}</NavLink>
      </Menu.Item>
    })
  }

  render() {
    return (
      <div>
        <div className="logo">
          <img src="/assets/logo-ant.svg" alt="" />
          <h1>CP CMS</h1>
          <Menu
            selectedKeys={this.state.currentKey}
            onClick={this.handleClick}
            theme="dark"
          >
            {this.state.menuTreeNode}
          </Menu>
        </div>
      </div>
    )
  }
}

export default connect()(NavLeft)